package com.example.demo.service.impl;

import com.example.demo.entity.*;
import com.example.demo.mapper.*;
import com.example.demo.security.jwt.JwtTokenUtil;
import com.example.demo.service.CourseService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CourseService courseService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private MajorMapper majorMapper;

    @Autowired
    private CourseRelationMapper courseRelationMapper;

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private ChangeCourseMapper changeCourseMapper;

    @Autowired
    private CourseMapperInt courseMapperInt;

    @Autowired
    private EduSystemMapper eduSystemMapper;

    @Override
    public User findUserById(String ID) {
        return userMapper.findUserByID(ID);
    }

    @Override
    public void saveToken(String id, String token) {
        User user = userMapper.findUserByID(id);
        user.setToken(token);
        userMapper.save(user);
    }

    @Override
    public boolean validateToken(String ID, String token) {
        String id = jwtTokenUtil.getUseridFromToken(token);
        return Objects.equals(id, ID);
    }



    //登录功能
    @Override
    public HashMap login(String ID, String password) {

        System.out.println("UserServiceImpl.login ID=" + ID + " password=" + password);
        String authority;
        HashMap hashMap = new HashMap();
        User user = userMapper.findUserByID(ID);
        //用户账号不存在
        if (user == null) {
            hashMap.put("message", "id not found");
            return hashMap;
        }
        //密码错误
        if (!Objects.equals(user.getPassword(), password)) {
            hashMap.put("message", "password is not correct");
        }
        //普通用户登录
        else {
            if (!Objects.equals(user.getRole(), "admin")) {
                hashMap.put("message", "normal login");
                authority = "user";
            }
            //管理员登录
            else {
                hashMap.put("message", "admin login");
                authority = "admin";
            }
            if(!Objects.equals(user.getUstatus(), "在读") && !Objects.equals(user.getUstatus(), "在岗"))
                hashMap.put("message","forbidden");

            hashMap.put("id", user.getID());
            hashMap.put("name", user.getName());
            hashMap.put("mail", user.getMail());
            hashMap.put("phonenumber", user.getPhoneNumber());
            hashMap.put("role", user.getRole());
            hashMap.put("identityid", user.getIdentityId());
            hashMap.put("firstlogin", user.getFirstLogin());
            hashMap.put("authorities", authority);
        }
        return hashMap;
    }

    @Override
    public List<String> changePwd(String ID, String oldPwd, String newPwd) {
        List<String> errorlist = new ArrayList<>();
        User user = userMapper.findUserByID(ID);

        if (user != null) {
            //密码错误
            if (!Objects.equals(user.getPassword(), oldPwd))
                errorlist.add("password is not correct");

            //新旧密码一致
            if (newPwd.equals(oldPwd))
                errorlist.add("The new password is identical to the last one password");
        } else {
            errorlist.add("userId not found");
        }


        if (errorlist.size() > 0)
            return errorlist;

        user.setFirstLogin(1);
        user.setPassword(newPwd);

        userMapper.save(user);
        return errorlist;
    }

    @Override
    public HashMap changeInf(String ID,String newmail, String newphonenumber) {
        HashMap hashMap = new HashMap();

        User user = userMapper.findUserByID(ID);

        boolean mailIsValid=true;
        boolean phoneIsValid=true;
        boolean isValid=true;

        if (user != null) {

            if (!newmail.equals("")) {
                User user1 = userMapper.findUserByMail(newmail);
                if (user1!=null&& !Objects.equals(user1.getID(), ID)) {
                    hashMap.put("mail", "邮箱与其他用户重复");
                    mailIsValid = false;
                }
                if(mailIsValid)
                    hashMap.put("mail","通过");
                if(newmail.equals(user.getMail())){
                    hashMap.put("mail","邮箱与原邮箱重复");
                }
            }
            else {
                hashMap.put("mail", "通过");
            }

            if (!newphonenumber.equals("")) {
                //与原号码重复
                User user1 = userMapper.findUserByPhonenumber(newphonenumber);
                if (user1!=null&& !Objects.equals(user1.getID(), ID)){
                    phoneIsValid = false;
                    hashMap.put("phonenumber","手机号与其他用户重复");
                }

                if(phoneIsValid)
                    hashMap.put("phonenumber","通过");

                if(newphonenumber.equals(user.getPhoneNumber())){
                    hashMap.put("phonenumber","手机号与原手机号重复");
                }
            }
            else{
                hashMap.put("phonenumber","通过");
            }


        } else {
            hashMap.put("id","user not found");
            isValid=false;
        }

        if(isValid&&mailIsValid&&phoneIsValid){
            user.setMail(newmail);
            user.setPhoneNumber(newphonenumber);
            userMapper.save(user);
        }

        return hashMap;
    }

    @Override
    public HashMap getInf(String ID){
        User user = userMapper.findUserByID(ID);
        HashMap hashMap = new HashMap();
        if(user==null) {
            hashMap.put("error", "user not found");
            return hashMap;
        }
        hashMap.put("firstlogin",user.getFirstLogin());
        hashMap.put("identityid",user.getIdentityId());
        hashMap.put("mail",user.getMail());
        hashMap.put("name",user.getName());
        hashMap.put("phonenumber",user.getPhoneNumber());
        hashMap.put("role",user.getRole());
        hashMap.put("umajor",user.getUmajor());
        hashMap.put("uschool",user.getUschool());
        hashMap.put("ustatus",user.getUstatus());

        return hashMap;

    }

//教师申请新增课程
    @Override
    public HashMap<String,String> addCourse(Course course,User teacher){
        HashMap<String,String> hashMap=courseService.validateCourse(course,teacher);
        if(Objects.equals(hashMap.get("result"), "success")){
            School school = schoolMapper.findSchoolByName(course.getCsname());
            Major major = majorMapper.findMajorByName(course.getCmname());
            course.setSchool(school);
            course.setMajor(major);
            course.setTeacher(teacher);
            courseMapper.save(course);
        }
        return hashMap;
    }

    //教师申请修改课程
    @Override
    public HashMap<String,String> changeCourse(ChangeCourse changeCourse, User teacher){
        String newTime = changeCourse.getCtime();
        String newRoom = changeCourse.getCroom();
        String newName = changeCourse.getCname();
        Integer cid = changeCourse.getCid();

        HashMap<String,String> resMap = new HashMap<>();

        if(!courseMapperInt.existsById(cid)){
            resMap.put("course","该课程不存在");
            resMap.put("result","fail");
            return resMap;
        }

        Course originalCourse = courseMapperInt.getById(cid);

        if(!Objects.equals(originalCourse.getCstatus(), "normal")){
            resMap.put("course","该课程不可修改");
            resMap.put("result","fail");
            return resMap;
        }
        boolean isValid = true;

        String croom =changeCourse.getCroom();
        boolean roomExists =false;
        if (roomMapper.existsById(croom)) {
            resMap.put("room", "ok");
            roomExists = true;
        } else {
            isValid = false;
            resMap.put("room", "教室不存在");
        }

        String[] time = newTime.split(",");

        for (String s : time) {
            int timeInt = Integer.parseInt(s);
            CourseRelation courseRelation = courseRelationMapper.findByRoomAndPeriod(timeInt, newRoom);
            if ( courseRelation!= null) {
                if (!Objects.equals(courseRelation.getCid(), cid)) {
                    isValid = false;
                    resMap.put("roomAvailable", "该时段该地点不空闲");
                    break;
                }
            }
            else {
                resMap.put("roomAvailable", "ok");
            }
        }


        for (String s : time) {
            int timeInt = Integer.parseInt(s);
            CourseRelation courseRelation = courseRelationMapper.findByTeacher(timeInt, teacher.getID());
            if ( courseRelation!= null) {
                if (!Objects.equals(courseRelation.getCid(), cid)) {
                    isValid = false;
                    resMap.put("teacher", "该时段该教师不空闲");
                    break;
                }
            }
            else {
                resMap.put("teacher", "ok");
            }
        }

        int count = 0;

        if(Objects.equals(newRoom, originalCourse.getCroom())){
            count++;
            resMap.put("compareRoom","和原教室重合");
        }
        else{
            resMap.put("compareRoom","ok");
        }

        String[] periodsStr = newTime.split(",");
        String[] ctimesStr = originalCourse.getCtime().split(",");
        boolean isSame = true;
        List<String> targetStr = new ArrayList<>();
        Collections.addAll(targetStr, ctimesStr);
        for (String s : periodsStr) {
            if (!targetStr.contains(s)) {
                isSame = false;
                break;
            }
        }

        if(isSame){
            count++;
            resMap.put("compareTime","和原时间重合");
        }
        else{
            resMap.put("compareTime","ok");
        }

        if(Objects.equals(newName, originalCourse.getCname())){
            count++;
            resMap.put("compareName","和原课程名重合");
        }
        else{
            resMap.put("compareName","ok");
        }

        if(roomMapper.findById(newRoom).isPresent()){
            resMap.put("roomExist","ok");
            Room newRoomEntity = roomMapper.findById(newRoom).get();
            if(newRoomEntity.getCapacity()<originalCourse.getCapacity()){
                isValid=false;
                resMap.put("roomCapacity","教室容量不足");
            }
            else{
                resMap.put("roomCapacity","ok");
            }
        }
        else{
            resMap.put("roomExist","教室不存在");
        }

        if(isValid && count<3){
            originalCourse.setCstatus("toChange");
            changeCourseMapper.save(changeCourse);
            resMap.put("result","success");
        }
        else{
            resMap.put("result","fail");
        }
        System.out.println("resMap.size: "+resMap.size());
        return resMap;
    }

    //教师申请删除课程功能
    @Override
    public Integer deleteCourse(Integer cid){
        Integer successCode = 200;
        Integer errCode = 500;

        Course course = courseMapperInt.getById(cid);
        if(Objects.equals(course.getCstatus(), "normal")) {
            course.setCstatus("toDelete");
            courseMapper.save(course);
            return successCode;
        }
        else{
            return errCode;
        }
    }

    //查看自己开设的课程或专业课程
    @Override
    public HashMap getMyOrMajorCourses(String id){
        HashMap resMap = new HashMap<>();

        //选课功能是否开启
        if(eduSystemMapper.findById("xk").isPresent()){
            if(!eduSystemMapper.findById("xk").get().isSysstatus()){
                resMap.put("error","选课功能未开启");
            }
        }

        User user = userMapper.getById(id);
        List<Course> courses = new ArrayList<>();
        if(Objects.equals(user.getRole(), "teacher")) {
            courses = courseMapper.findByTidAndStatus(id,"normal","toChange","toDelete");
            resMap.remove("error");
        }
        if(Objects.equals(user.getRole(), "student")){
            if(resMap.get("error")!=null)
                return resMap;
            String mname = user.getUmajor();
            courses = courseMapper.findByCmnameAndStatus(mname,"normal","toChange","toDelete");
        }
        resMap.put("res",courses);
        resMap.put("total",courses.size());
        return resMap;
    }

    //教师查看所有教室
    @Override
    public HashMap UserGetRooms(String id){
        User user = userMapper.getById(id);
        HashMap resMap = new HashMap<>();
        if(!Objects.equals(user.getRole(), "teacher")){
            resMap.put("error","身份验证失败");
            return resMap;
        }
        List<Room> rooms = roomMapper.findAll();
        resMap.put("res",rooms);
        resMap.put("total",rooms.size());
        return resMap;
    }


}
